<template>
  <div class="news-page__container">
    <div class="news-page__header">
      <news-hot-spot :trend="trend" />
      <news-ranking :list="rankingList" :sourceType="rankSource" @refresh="handleRefresh" @select="handleSelect" />
    </div>
    <div class="news-page__content">
      <el-carousel :interval="5000" height="100%" arrow="hover" indicator-position="none">
        <el-carousel-item v-for="(group, index) in groupedItems" :key="index">
          <news-card v-for="item in group" :key="item.id" :sourceLogo="item.logo" :sourceType="item.sourceTypeCn" :list="item.list" :intervalTime="item.intervalTime" />
        </el-carousel-item>
      </el-carousel>
    </div>
  </div>
</template>

<script>
import _ from 'lodash'

export default {
  name: 'NewsIndex',
  components: {
    NewsCard: () => import('./components/Card'),
    NewsRanking: () => import('./components/Ranking'),
    NewsHotSpot: () => import('./components/HotSpot')
  },
  data() {
    return {
      items: [],
      rankSource: null,
      rankingList: [],
      trend: null,
      itemsPerPage: 3,
      resizeObserver: null,
      refreshInterval: null
    }
  },
  computed: {
    groupedItems() {
      const groups = []
      for (let i = 0; i < this.items.length; i += this.itemsPerPage) {
        groups.push(this.items.slice(i, i + this.itemsPerPage))
      }
      return groups
    }
  },
  created() {
    this.f5()
    this.updateItemsPerPage()
  },
  mounted() {
    this.initResizeObserver()
    this.startAutoRefresh()
  },
  beforeDestroy() {
    this.cleanupResizeObserver()
    this.stopAutoRefresh()
  },
  methods: {
    initResizeObserver() {
      try {
        const debouncedUpdate = _.debounce(() => {
          this.updateItemsPerPage()
        }, 150)

        this.resizeObserver = new ResizeObserver((entries) => {
          requestAnimationFrame(() => {
            if (!Array.isArray(entries) || !entries.length) return
            debouncedUpdate()
          })
        })

        if (this.$el) {
          this.resizeObserver.observe(this.$el)
        }
      } catch (error) {
        this.cleanupResizeObserver()
      }
    },

    cleanupResizeObserver() {
      if (this.resizeObserver) {
        try {
          this.resizeObserver.disconnect()
        } finally {
          this.resizeObserver = null
        }
      }
    },

    f5() {
      this.fetchDate()
      this.fetchTrend()
    },
    fetchDate() {
      sa.ajax('/top/hots', (res) => {
        this.items = res.data
      }, {
        type: 'get'
      })
    },
    fetchTrend() {
      sa.ajax('/top/trend', {
        day: -1,
        timestamp: new Date().getTime(),
      }, (res) => {
        this.trend = res.data
      }, {
        type: 'get'
      })
    },
    handleRefresh() {
      // 随机选择一个item并获取其list的前三条
      const randomItem = _.sample(this.items)
      if (randomItem && randomItem.list) {
        this.rankingList = _.take(randomItem.list, 3);
        this.rankSource = randomItem.sourceTypeCn;
      } else {
        this.rankingList = []
      }
    },
    handleSelect(item) {
      sa.go(item.nextUrl)
    },
    updateItemsPerPage: _.debounce(function () {
      try {
        if (!this.$el) return
        const containerWidth = this.$el.clientWidth
        if (containerWidth < 768) {
          this.itemsPerPage = 1
        } else if (containerWidth < 1200) {
          this.itemsPerPage = 2
        } else {
          this.itemsPerPage = 3
        }
        // Force Vue to update the view
        this.$forceUpdate()
      } catch (error) {
        console.error('Failed to update items per page:', error)
      }
    }, 150), // Increased debounce time for better performance

    startAutoRefresh() {
      this.refreshInterval = setInterval(() => {
        this.f5()
      }, 30000)
    },
    stopAutoRefresh() {
      if (this.refreshInterval) {
        clearInterval(this.refreshInterval)
        this.refreshInterval = null
      }
    }
  },
  watch: {
    items: {
      handler() {
        this.handleRefresh()
      },
      deep: true
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/mixin.scss';

.news-page__container {
  @include flex-column;
  height: 100%;
  width: 100%;
  padding: 12px;
  gap: 12px;
  min-width: 160px;
  overflow: auto;

  @media (max-width: 1200px) {
    padding: 8px;
    gap: 8px;
  }

  @media (max-width: 768px) {
    padding: 4px;
    gap: 4px;
  }
}

.news-page__header {
  @include flex-center;
  height: 20%;
  width: 100%;
  border-radius: 12px;
  transition: all 0.3s ease;
  gap: 20px;

  @media (max-width: 1200px) {
    padding: 16px;
    border-radius: 10px;
  }

  @media (max-width: 768px) {
    padding: 12px;
    border-radius: 8px;
    flex-direction: column;
    gap: 12px;
  }
}

.news-page__content {
  @include flex-center;
  height: calc(100% - 160px);
  width: 100%;
  min-height: 400px;
  overflow: hidden;
  border-radius: 12px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  background-color: #fff;

  @media (max-width: 1200px) {
    min-height: 360px;
    border-radius: 10px;
  }

  @media (max-width: 768px) {
    min-height: 300px;
    border-radius: 8px;
  }
}

::v-deep .el-carousel--horizontal {
  overflow-x: visible !important;
}

.el-carousel {
  width: 100%;
  height: 100%;
  padding: 12px;

  @media (max-width: 1200px) {
    padding: 8px;
  }

  @media (max-width: 768px) {
    padding: 4px;
  }

  ::v-deep .el-carousel__item {
    $gap: 30px;

    display: flex;
    flex-wrap: nowrap;
    gap: $gap;
    box-sizing: border-box;
    overflow: hidden;
    border-radius: 12px;
    transition: all 0.3s ease;
    padding: 12px;

    @media (max-width: 1200px) {
      gap: 16px;
      padding: 8px;
    }

    @media (max-width: 768px) {
      gap: 12px;
      padding: 4px;
    }

    &>* {
      flex: 1 1 0;
      min-width: 0;
      border-radius: 8px;
      transition: all 0.3s ease;
      transform: scale(1.02);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

      @media (max-width: 1200px) {
        flex: 1 1 50%;
        margin: 0 4px;
      }

      @media (max-width: 768px) {
        flex: 1 1 100%;
        margin: 0;
        padding: 12px;
        border-radius: 6px;
        transform: none;
      }
    }
  }

  ::v-deep .el-carousel__arrow {
    background-color: rgba(0, 0, 0, 0.3);
    color: #fff;
    width: 40px;
    height: 40px;
    font-size: 20px;

    @media (max-width: 768px) {
      width: 32px;
      height: 32px;
      font-size: 16px;
    }
  }

  ::v-deep .el-carousel__arrow:hover {
    background-color: rgba(0, 0, 0, 0.5);
  }
}
</style>
